from obs import GetObjectHeader
from obs import ObsClient
import traceback
import os
import time


SECRET_KEY = 'django-insecure-7(qr@il524$2ins)^#d7-_+ggj(3-9o0^l@bisy_85j^^%#(81'

OBS_ACCESS_KEY  = '9GNUENAZSX0UIN5WHJ9R'
OBS_SECRET_KEY  = 'umhOAm01wR65ldrG6tkic1mfMaKD8xaOHbrnkOa3'
OBS_SERVER = "https://obs.cn-north-4.myhuaweicloud.com"

ak = OBS_ACCESS_KEY
sk = OBS_SECRET_KEY
server = OBS_SERVER
obsClient = ObsClient(
    access_key_id=ak,
    secret_access_key=sk,
    server=server
)

def get_obs_num(obs_name):
    try:
        bucketName = obs_name
        # 获取桶的存量信息
        resp = obsClient.getBucketStorageInfo(bucketName)
        # 返回码为2xx时，接口调用成功，否则接口调用失败
        if resp.status < 300:
            print('objectNumber:', resp.body.objectNumber)
            return resp.body.objectNumber
        else:
            print('Get Bucket StorageInfo Failed')
            print('requestId:', resp.requestId)
            print('errorCode:', resp.errorCode)
            print('errorMessage:', resp.errorMessage)
    except:
        print('Get Bucket StorageInfo Failed')
        print(traceback.format_exc())

# anomaly_num = get_obs_num('textile-anomaly')
# print(anomaly_num)



def download_image(bucket_name, object_key, download_dir, save_as):
    try:
        if not os.path.exists(download_dir):
            os.makedirs(download_dir)
        
        # 下载对象的附加头域
        headers = GetObjectHeader()
        
        # 下载到本地的路径, save_as 为包含本地文件名称的全路径
        download_path = os.path.join(download_dir, save_as)
        
        # 文件下载
        resp = obsClient.getObject(bucket_name, object_key, download_path, headers=headers)
        
        # 返回码为2xx时，接口调用成功，否则接口调用失败
        if resp.status < 300:
            print(f'Get Object Succeeded: {object_key}')
            print(f'Downloaded to: {download_path}')
        else:
            print(f'Get Object Failed: {object_key}')
            print('requestId:', resp.requestId)
            print('errorCode:', resp.errorCode)
            print('errorMessage:', resp.errorMessage)
    except Exception as e:
        print('Get Object Failed') 
        print(traceback.format_exc())

# 设置本地下载目录

def download_latest_images(bucket_name, download_dir, flag):
    # 获取桶内对象的总数
    total_objects = get_obs_num(bucket_name)
    if total_objects < 2:
        print(f"Not enough objects in {bucket_name} to download 2 images.")
        return
    
    # 获取当前时间戳
    current_timestamp = time.strftime('%Y%m%d%H%M%S')

    # 最新的两张图片对应的文件名
    latest_image_key = f"{total_objects}.jpg"
    
    # 下载最新的图片并附上当前时间戳
    if flag == "anomaly":
        download_image(bucket_name, latest_image_key, download_dir, save_as=f"{current_timestamp}_{total_objects}_anomaly.jpg")
        download_image(bucket_name, latest_image_key, download_dir, save_as=f"./static/img/latest_images/anomaly1.jpg")
    else:
        download_image(bucket_name, latest_image_key, download_dir, save_as=f"{current_timestamp}_{total_objects}_normal.jpg")
        download_image(bucket_name, latest_image_key, download_dir, save_as=f"./static/img/latest_images/normal1.jpg")


def main():
    download_dir = "./static/img/device1/"
    previous_num = get_obs_num('textile-anomaly')
    
    while True:
        current_num = get_obs_num('textile-anomaly')
        if current_num != previous_num:
            print("New files detected, downloading...")
            download_latest_images("textile-anomaly", download_dir, flag="anomaly")
            download_latest_images("textile-anomaly-original", download_dir, flag="original")
            previous_num = current_num
        time.sleep(1)  # 每3秒检查一次

if __name__ == "__main__":
    main()